/**
 * Created by zhoulin on 2019/4/3.
 */
var companyId = sessionStorageUtils.getJson(storageKey.sessionStorageKey.companyId);
var schoolId = sessionStorageUtils.getJson(storageKey.sessionStorageKey.schoolId);
var schoolMap = sessionStorageUtils.getJson(storageKey.sessionStorageKey.schoolMap);
var isVideo = 0;

var app = new Vue({
    el: '#app',
    data: {
        permissions:['banner:add','banner:update'],//本页权限数组
        selects:[],
        desc:'',
        schoolId:schoolId,
        schoolList:schoolMap,
    },
    //进入页面初始化方法
    created: function () {
        var that = this;
        that.getDicList("banner");
        var token = sessionStorageUtils.getJson(storageKey.sessionStorageKey.token);
        if(empty(token)){
            layer.msg("<span style='color:red'>登录超时！请重新登录！</span>", {time: 1500, icon:5});
            setTimeout(function () {
                window.location.href = _LOGIN_PAGE;
            },1200);

            return ;
        }
        if(!empty(aGET.id)){
            that.getInfoById(aGET.id);
        }
    },
    methods: {
        //权限控制
        permission: function (index) {
            return (_PERMISSIONS.indexOf(this.permissions[index]) != -1);
        },
        // 得到字典map
        getDicList: function(keyTable) {
            var that = this;
            Get(that,_HOST+_API.common_dic_dicList+"?keyTable="+keyTable)
                .then(function (response) {
                    // 响应成功回调
                    console.log(response);
                    if(response){
                        if(response.success){
                            that.selects = response.list;
                        }else {
                            layer.msg(response.msg, {time: 1500, icon:5});
                        }
                    }
                });
        },
        getInfoById:function (id) {
            var that = this;
            Get(that,_HOST+_API.common_banner_getById+"?id="+id)
                .then(function (response) {
                    // 响应成功回调
                    console.log(response);
                    if(response){
                        if(response.success){
                            var list = response.data;
                            var oldImgId = "";
                            for (var item in list) {
                                if (item == 'imgId') {
                                    oldImgId = list[item];
                                }
                                if (item == 'showUrl') {
                                    initFileUpload(list[item]);
                                }
                                if (item == 'description') {
                                    that.desc = list[item];
                                }
                                if (item == 'type') {
                                    $("#Form select[name='type']").val(list[item]);
                                }
                                if (item == 'schoolId') {
                                    $("#Form select[name='schoolId']").val(list[item]);
                                }
                                $("#Form input[name='" + item + "']").val(list[item]);
                            }
                            $("#Form input[name='oldImgId']").val(oldImgId);
                            $("#Form").data('bootstrapValidator').destroy();
                            $('#Form').data('bootstrapValidator', null);
                            Validator();
                        }else {
                            layer.msg(response.msg, {time: 1500, icon:5});
                        }
                    }
                })
        },
        // 添加
        add:function () {
            var that = this;
            var param = formToJson($('#Form').find(":not(input[name='herfUrl'])").serialize());
            param['companyId'] = companyId;
            param['isVideo'] = isVideo;
            param['herfUrl'] = $("#Form input[name='herfUrl']").val();
            //console.log(param)
            Post(that,_HOST+_API.common_banner_add,param,true,that.permissions[0])
                .then(function (response) {
                    // 响应成功回调
                    console.log(response);
                    if(response){
                        if(response.success){
                            layer.msg(response.msg, {time: 1500, icon:1});
                            setTimeout(function () {
                                window.parent.location.reload(); //刷新父页面
                                layer.closeAll();
                            }, 1500)
                        }else {
                            layer.msg(response.msg, {time: 1500, icon:5});
                        }
                    }
                    $("#Form").data('bootstrapValidator').destroy();
                    $('#Form').data('bootstrapValidator', null);
                    Validator();
                })
        },
        // 修改
        update:function () {
            var that = this;
            var param = formToJson($('#Form').find(":not(input[name='herfUrl'])").serialize());
            param['companyId'] = companyId;
            param['isVideo'] = isVideo;
            param['herfUrl'] = $("#Form input[name='herfUrl']").val();
             // console.log(param)
            Post(that,_HOST+_API.common_banner_update,param,true,that.permissions[1])
                .then(function (response) {
                    // 响应成功回调
                    console.log(response);
                    if(response){
                        if(response.success){
                            layer.msg(response.msg, {time: 1500, icon:1});
                            setTimeout(function () {
                                window.parent.location.reload(); //刷新父页面
                                layer.closeAll();
                            }, 1500)
                        }else {
                            layer.msg(response.msg, {time: 1500, icon:5});
                        }
                    }
                    $("#Form").data('bootstrapValidator').destroy();
                    $('#Form').data('bootstrapValidator', null);
                    Validator();
                })
        },
    },
});

function initFileUpload (url) {
    $("#fileUpload").fileinput({
        language: "zh",
        uploadUrl: _HOST+_API.common_file_ossUpload,
        ajaxSettings:{
            headers: {
                'Authorization': sessionStorageUtils.getJson(storageKey.sessionStorageKey.token),
                'permCoding': ''
            }
        },
        browseClass: "btn btn-success",
        browseLabel: "上传预览文件",
        browseIcon: "<i class=\"glyphicon glyphicon-picture\"></i> ",
        allowedFileExtensions: ['jpg', 'gif', 'png', "avi", "mov", "rmvb", "rm", "flv", "mp4"],
        showUpload: false,
        dropZoneEnabled: true,
        showPreview: true,
        minFileCount: 1,
        maxFileCount: 1,
        initialPreviewAsData: true,
        initialPreview: [
            url
        ],
        initialPreviewConfig: [
            {
                caption: url,
                type: getFileType(url),
                filetype: getFileTypes(url),
                // size: 329892,
                width: "120px",
                url: url,
                key: 1
            },
        ]
    }).on("filebatchselected", function (event, files) {
        $(this).fileinput("upload");
    }).on("fileuploaded", function (event, data, previewId, index) {
        if (data.response.status) {
            console.log(data.response);
            getFileType(data.response.fileUrl);
            $(".file-caption-name").text(data.response.attachemId);
            $("#articleImg").val(data.response.attachemId);
        } else {
            parent.layer.msg(data.response.msg, {time: 1500, icon: 5});
        }
    });
    $(".kv-file-remove").remove();
}

function getFileType(url) {
    var type = "video";
    isVideo = 1;
    if(url.indexOf("jpg") >= 0 || url.indexOf("gif") >= 0 || url.indexOf("png") >= 0) {
        type = "image";
        isVideo = 0;
    }
    return type;
}

function getFileTypes(url) {
    var type = "";
    // "avi", "mov", "rmvb", "rm", "flv", "mp4"
    if (url.indexOf("jpg") >= 0) {
        type = "image/jpg";
    } else if (url.indexOf("gif") >= 0) {
        type = "image/gif";
    } else if (url.indexOf("png") >= 0) {
        type = "image/png";
    } else if (url.indexOf("avi") >= 0) {
        type = "video/avi";
    } else if (url.indexOf("mov") >= 0) {
        type = "video/mov";
    } else if (url.indexOf("rmvb") >= 0) {
        type = "video/rmvb";
    } else if (url.indexOf("rm") >= 0) {
        type = "video/rm";
    } else if (url.indexOf("flv") >= 0) {
        type = "video/flv";
    } else if (url.indexOf("mp4") >= 0) {
        type = "video/mp4";
    }
    return type;
}

$(function () {
    if(empty(aGET.id)){
        initFileUpload('');
    }
});

$('#Form').data('bootstrapValidator', null);
Validator();
function Validator() {
    $('#Form').bootstrapValidator({
        fields: {
            title: {
                validators: {
                    notEmpty: {
                        message: '名称不能为空'
                    },
                    stringLength: {
                        max: 50,
                        message: '名称长度最多50个字符'
                    },
                }
            },
            type: {
                validators: {
                    notEmpty: {
                        message: '请选择类别'
                    },
                }
            },
            description: {
                validators: {
                    stringLength: {
                        max: 500,
                        message: '描述长度最多500个字符'
                    },
                }
            },
            herfUrl: {
                validators: {
                    /*notEmpty: {
                        message: '跳转地址不能为空'
                    },*/
                    stringLength: {
                        max: 500,
                        message: '跳转地址长度最多500个字符'
                    },
                   /* stringLength: {
                        min: 5,
                        message: '跳转地址长度最少5个字符以上'
                    },*/
                }
            },
            sort: {
                validators: {
                    notEmpty: {
                        message: '排序不能为空'
                    },
                }
            }
        }
    }).on('success.form.bv', function (e) {
        // Prevent form submission
        e.preventDefault();
        if(empty(aGET.id)){
            app.add();
        }else {
            app.update();
        }
    });
}
